/**
 * Copyright (C) 2012 Oleg Anastassov <o.anastasov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.ent.business.server.impl;

import kz.kstu.ent.business.common.exception.LoginFailedException;
import kz.kstu.ent.business.entity.QueryNames;
import kz.kstu.ent.business.entity.security.Account;
import kz.kstu.ent.business.server.api.AccountService;
import org.jasypt.util.password.BasicPasswordEncryptor;

import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.security.auth.login.AccountException;
import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.LoginException;
import java.util.List;

/**
 * @author Oleg Anastassov
 *         created: 08.09.11 15:42
 */
public class AccountServiceImpl extends AbstractService implements AccountService {

    @Override
    public void register(String login, String password, boolean isAdmin) throws AccountException {
        Query query = getEntityManager().createNamedQuery(QueryNames.FIND_ACCOUNT_BY_LOGIN);
        query.setParameter("login", login);
        List<Account> accounts = query.getResultList();

        if (accounts.size() > 0) {
            throw new AccountException("Login already exists");
        }

        Account account = new Account();
        account.setLogin(login);
        BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
        String encryptedPassword = passwordEncryptor.encryptPassword(password);
        account.setPassword(encryptedPassword);
        account.setAdmin(isAdmin);
        getEntityManager().persist(account);
    }

    @Override
    public Account login(String login, String password) throws LoginException {
        Query query = getEntityManager().createNamedQuery(QueryNames.FIND_ACCOUNT_BY_LOGIN);
        query.setParameter("login", login);
        Account account;
        try {
            account = (Account) query.getSingleResult();
        } catch (NoResultException e) {
            throw new AccountNotFoundException("Account with login = '" + login + "' not found");
        }

        String passwordInDB = account.getPassword();
        BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
        boolean isValid = passwordEncryptor.checkPassword(password, passwordInDB);
        if (isValid) {
            return account;
        } else {
            throw new LoginFailedException("Check authentication data filed");
        }
    }

    @Override
    public void changePassword(String login, String newPassword) throws AccountNotFoundException {
        Query query = getEntityManager().createNamedQuery(QueryNames.FIND_ACCOUNT_BY_LOGIN);
        query.setParameter("login", login);
        Account account;
        try {
            account = (Account) query.getSingleResult();
        } catch (NoResultException e) {
            throw new AccountNotFoundException("Account with login = '" + login + "' not found");
        }
        BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
        String encryptedPassword = passwordEncryptor.encryptPassword(newPassword);
        account.setPassword(encryptedPassword);
        getEntityManager().persist(account);
    }

    public int getUserCount() {
        Query query = getEntityManager().createNamedQuery(QueryNames.FIND_ALL_ACCOUNTS);
        List<Account> accounts = query.getResultList();
        return accounts.size();
    }
}
